<template>
  <div>
    <div class="form-box">
      <el-input v-model="count" class="count-input" />
      <el-button type="primary" @click="createCode">确定</el-button>
      <el-button type="warning" size="large" @click="multiUpload">点击上传</el-button>
    </div>
    <div class="code-list" 
      v-loading="loading"
      :element-loading-text="loadText">
      <ul>
        <li class="qqq" v-for="(item,index) in countArr" :key="item+index">
          <div class="qrCode" ref="qrCodeDiv"></div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
import html2canvas from "html2canvas";
export default {
  name: "qrCode",
  data() {
    return {
      count: 1,
      countArr: [],
      imgDataArr: [],
      loading: false,
      loadText: '生成中...'
    };
  },
  mounted: function () {
    // this.$nextTick(function () {
    //   this.bindQRCode();
    // });
  },
  methods: {
    createCode(){
      this.countArr = [];
      this.imgDataArr = [];
      for(let i=0;i<this.count;i++){
        let num = Math.random()+i
        this.countArr.push(num)
      }
      this.$nextTick(()=>{
        this.loadText = '生成中...'
        this.loading = true;
        for(let i=0;i<this.count;i++){
          this.bindQRCode(i)
        }
        this.loading = false;
      })
    },
    bindQRCode(index) {
      let url = "http://xcaipu.cn/";
      new QRCode(this.$refs.qrCodeDiv[index], {
        text: url,
        width: 200,
        height: 200,
        colorDark: "#333333", // 二维码颜色
        colorLight: "#ffffff", // 二维码背景色
        correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
      });
      this.createPicture(index);
    },
    //将二维码=生成图片
    createPicture(index) {
      const that = this;
      html2canvas(this.$refs.qrCodeDiv[index], {
        backgroundColor: null,
        width: 200,
        height: 200,
      }).then((canvas) => {
        console.log('canvas',canvas);
        // var imgData = canvas.toDataUrl("image/jpeg");
        var imgData = canvas.toDataURL()

        // that.imgData = imgData;
        this.imgDataArr.push(imgData)
        // console.log("this.imgData", that.imgData);
      });
      // }原文链接：https://blog.csdn.net/bullcode/article/details/125283126
    },
    dataURLtoFile(dataurl, filename='file') {
      //将base64转换为文件
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type:mime});
    },
    // 睡眠函数
    sleep(delay){
      return new Promise((resolve,reject)=>{
        setTimeout(()=>{
          resolve()
        }, delay)
      })
    },
    async multiUpload(){
      this.loadText = '上传中...'
      this.loading = true;
      // 准备上传文件数据
      for(let i=0;i<this.imgDataArr.length;i++){
        let formData = new FormData();
        const name = `qrCode_${i}.png`
        const file = this.dataURLtoFile(this.imgDataArr[i], name)
        // console.log('file',file);
        formData.append("isAdd", 'isAdd');
        formData.append("file", file); // 图片
        formData.append("name", name); // 主题
        formData.append("desc", name); // 描述
        await this.uploadImg(formData)
        // 睡眠2秒，再传下一张图片，避免服务器阻塞报错
        await this.sleep(1000)
      }
      this.loading = false;
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.$router.push('/imgList')
    },
    uploadImg(formData){
      return new Promise((resolve,reject)=>{
        // axios接收文件格式数据 https://blog.csdn.net/m0_38069630/article/details/79105709
        let config = {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };
        this.$axios
        .post(window.API + "/fileUpload", formData, config)
        .then((res) => {
          console.log("提交:", res);
          if (res.data.error == 0) {
            this.showDialog = false;
            resolve(true)
          } else {
            let msg = res.data.msg;
            if (msg == "{}") {
              msg = "";
            }
            this.$message({
              message: "服务器出错" + msg,
              type: "error",
            });
            reject("服务器出错" + msg)
          }
        })
        .catch((err) => {
          console.log("出错", err);
          this.$message({
            message: "服务器出错!",
            type: "error",
          });
          reject("服务器出错" + err)
        });
      })
    }
  },
};
// 原文链接：https://blog.csdn.net/weixin_50241387/article/details/123549095
</script>

<style scoped>
.code-list ul{
  display: flex;
  flex-wrap: wrap;
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  align-content: flex-start;
}
.code-list li{
  list-style: none;
  margin-bottom: 15px;
  margin-right: 15px;
  width: 230px;
}
.form-box{
  padding: 10px 0;
  margin: 10px 0;
  border-bottom:1px solid #ccc;
}
.count-input{
  width: 200px;
}
.qqq {
  background-color: rgb(0, 145, 255);
  width: 220px;
  height: 220px;
  margin: 0 auto; /*水平居中*/
  position: relative;
}
.qrCode {
  display: inline-block;
  margin: 0 auto; /*水平居中*/
  position: relative;
  top: 10px;
}
.qrCode img {
  width: 200px;
  height: 200px;
  background-color: #fff;
  padding: 6px;
}
</style>